/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.fragment;

import java.util.List;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.StopsIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TaskIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TracksIntentHolder;
import lt.marsrutai.mobile.android.adapter.TrackAdapter;
import lt.marsrutai.mobile.android.fragment.task.GetTracksTaskFragment;
import lt.marsrutai.mobile.android.fragment.task.TaskFragment;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.Track;
import lt.marsrutai.mobile.android.task.GetTracksTask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;


public class TracksFragment extends SherlockListFragment {

    private static final String GET_TRACKS_TASK_FRAGMENT_TAG = "getBookmarkedStops";
    
    private FragmentManager fragmentManager;
    private ActivityManager manager;

    private TrackAdapter adapter;
    
    private List<Track> tracks;

    private String scopeFolder;
    private String scopeName;
    private String transportId;
    private String scheduleTrackName;
    private String scheduleId;
    private String scheduleName;
    private String[] trackIds;

    private BroadcastReceiver tracksReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TaskIntentHolder holder = new TaskIntentHolder(intent);

            switch (holder.getStatus()) {
                case Activity.RESULT_OK:
                    tracks = holder.getListResult();
                    
                    fillAdapter();
                    manager.dismissDownloadLoadingBar();
                    break;
                case GetTracksTask.RESULT_NOT_RESOLVED:
                    manager.runOnUiThread(manager.errorRes);
                    break;
                default:
                    manager.dismissDownloadLoadingBar();
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(tracksReceiver, new IntentFilter(GetTracksTask.BROADCAST_ACTION));

        if (tracks == null) {
            // Check whether the worker fragment has been retained
            TaskFragment<?, ?, ?> taskFragment = (TaskFragment<?, ?, ?>) fragmentManager.findFragmentByTag(GET_TRACKS_TASK_FRAGMENT_TAG);
    
            // Start downloading only if we don't have any scopes, and task fragments has not been retained
            if (!TaskFragment.isActive(taskFragment)) {
                downloadData();
            }
        }
        else {
            // already have all the data - display it
            fillAdapter();
            manager.dismissDownloadLoadingBar();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(tracksReceiver);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.list_fragment, null);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fragmentManager = getFragmentManager();
        manager = new ActivityManager(getActivity());
        manager.showDownloadLoadingBar();

        // Restore state
        receiveItemData(savedInstanceState);
    }

    private void downloadData() {
        TaskFragment.download(fragmentManager, 
                GetTracksTaskFragment.class, GET_TRACKS_TASK_FRAGMENT_TAG,
                new GetTracksTask.Criteria[] { new GetTracksTask.Criteria(scopeFolder, scheduleId, trackIds) });
    }

    private void fillAdapter() {
        adapter = new TrackAdapter(getActivity(), bundleState());
        adapter.setTracks(tracks);
        
        setListAdapter(adapter);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        int resolvedPosition = adapter.resolveItemPosition(position);
        if (resolvedPosition >= 0) {
            sendItemData(resolvedPosition);
        }
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putAll(bundleState());
        super.onSaveInstanceState(outState);
    }

    protected Bundle bundleState() {
        TracksIntentHolder intentHolder = new TracksIntentHolder(new Bundle());
        intentHolder.setTracks(tracks);
        intentHolder.setScopeFolder(scopeFolder);
        intentHolder.setScopeName(scopeName);
        intentHolder.setTransportId(transportId);
        intentHolder.setScheduleId(scheduleId);
        intentHolder.setScheduleName(scheduleName);
        intentHolder.setScheduleTrackName(scheduleTrackName);
        intentHolder.setTrackIds(trackIds);
        return intentHolder.getIntent().getExtras();
    }

    public void receiveItemData(Bundle bundle) {
        TracksIntentHolder intentHolder = new TracksIntentHolder(bundle == null ? getArguments() : bundle);
        tracks = intentHolder.getTracks();
        scopeFolder = intentHolder.getScopeFolder();
        scopeName = intentHolder.getScopeName();
        transportId = intentHolder.getTransportId();
        scheduleId = intentHolder.getScheduleId();
        scheduleName = intentHolder.getScheduleName();
        scheduleTrackName = intentHolder.getScheduleTrackName();
        trackIds = intentHolder.getTrackIds();
    }

    public void sendItemData(int i) {
        Track track = tracks.get(i);
        StopsIntentHolder intentHolder = new StopsIntentHolder(getActivity(),
            scopeFolder,
            scopeName,
            transportId,
            scheduleId,
            scheduleName,
            scheduleTrackName,
            track.getId(),
            track.getName()
        );
        startActivity(intentHolder.getIntent());
    }

}
